<template>
  <div>
    <!-- 结果列表 -->
    <el-card>
      <el-table :data="mailList" stripe style="width: 100%">
        <el-table-column label="#" width="80">
          <template slot-scope="scope">
            {{ (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" width="400">
          <template slot-scope="scope">
            <div class="content-preview" v-html="getPreviewContent(scope.row.content)"></div>
            <el-button v-if="shouldShowButton(scope.row.content)" type="text" @click="toggleShowFullContent(scope.row)">查看全部</el-button>
          </template>
        </el-table-column>

        <!-- 回复列 -->
        <el-table-column prop="reply" label="回复" width="400">
          <template slot-scope="scope">
            <div class="content-preview" v-html="getPreviewContent(scope.row.reply)"></div>
            <el-button v-if="shouldShowButton(scope.row.reply)" type="text" @click="toggleShowFullReply(scope.row)">查看全部</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="提交时间" width="150">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="公开" width="120">
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.isPublic"
                :active-value="1"
                :inactive-value="0"
                @change="handlePublicChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                circle
                @click="openReplyUI(scope.row.id)"
            />
            <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
                @click="deleteMail(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 在 el-card 下方增加两个按钮，并通过样式美化它们 -->
    <div class="button-container">
      <el-button type="primary" @click="queryUnreplied">查询未回复信件</el-button>
      <el-button type="primary" @click="queryAll">查询全部信件</el-button>
    </div>

    <!-- 分页组件 -->
    <el-pagination
        :current-page="searchModel.pageNo"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="searchModel.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 回复弹窗 -->
    <el-dialog
        title="回复邮件"
        :visible="dialogFormVisible"
        width="50%"
        @close="dialogFormVisible = false"
        transition="dialog-fade"
    >
      <el-form :model="userForm" :rules="rules" ref="userForm" label-width="80px" style="display: flex; flex-direction: column;">
        <el-form-item label="回复内容" prop="reply" style="flex: 1;">
          <quill-editor v-if="dialogFormVisible" v-model="userForm.reply" :style="{ width: '100%', height: '300px' }"></quill-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitReply">提交回复</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mailList, setPublic, deleteMailById, setReply } from '../../../../api/mail'
import truncate from 'truncate-html'

export default {
  name: 'Mail',
  data () {
    return {
      formLabelWidth: '80px',
      title: '',
      total: 0,
      searchModel: {
        num: 3,
        pageNo: 1,
        pageSize: 10
      },
      mailList: [],
      dialogFormVisible: false,
      userForm: {
        reply: ''
      },
      rules: {
        reply: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.getMailList()
  },
  methods: {
    formatDate (date) {
      if (!date) return '' // 处理日期为空的情况

      // 将日期字符串解析为日期对象
      const datee = new Date(date.replace(/T/, ' ').replace(/Z/, ''))

      // 判断是否成功解析
      if (!isNaN(datee.getTime())) {
        // 使用 toLocaleDateString 获取年月日部分
        return datee.toLocaleDateString('en-US', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        })
      } else {
        return 'Invalid Date'
      }
    },
    // 查询未回复信件
    queryUnreplied () {
      this.searchModel.num = 0 // 设置为0代表查询未回复的信件
      this.getMailList() // 触发查询
    },

    // 查询全部信件
    queryAll () {
      this.searchModel.num = 3 // 设置为3代表查询全部信件
      this.getMailList() // 触发查询
    },
    getPreviewContent (content) {
      // 调用 truncate 函数进行 HTML 富文本的截断
      const truncatedContent = truncate(content, 5, { byWords: true })
      return truncatedContent
    },
    shouldShowButton (content) {
      function escapeHtml (html) {
        const textArea = document.createElement('textarea')
        textArea.innerHTML = html
        return textArea.value
      }

      function getEscapedContentLength (content) {
        const escapedContent = escapeHtml(content)
        // 使用 truncate 函数获取截断后的 HTML 富文本的长度
        const truncatedContent = truncate(escapedContent, 5, { byWords: true })
        return truncatedContent.length
      }

      // 如果内容长度超过某个阈值，显示按钮
      return getEscapedContentLength(content) > 5
    },
    toggleShowFullContent (row) {
      // 在这里可以使用弹窗或者折叠面板等方式展示完整内容
      this.$alert(row.content, '完整内容', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true
      })
    },
    toggleShowFullReply (row) {
      // 在这里可以使用弹窗或者折叠面板等方式展示完整回复
      this.$alert(row.reply, '完整回复', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true
      })
    },
    openReplyUI (id) {
      // 打开回复弹窗
      this.dialogFormVisible = true
      this.userForm = {
        id: id,
        reply: ''
      }
    },
    submitReply () {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          // 提交回复
          const mailDTO = {
            id: this.userForm.id,
            reply: this.userForm.reply
          }
          setReply(mailDTO)
            .then(response => {
              this.$message({
                type: 'success',
                message: response.message
              })
              // 关闭弹窗
              this.dialogFormVisible = false
              // 刷新邮件列表
              this.getMailList()
            })
            .catch(error => {
              console.error(error)
            })
        } else {
          return false
        }
      })
    },
    deleteMail (row) {
      this.$confirm(`您确认删除该信件 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteMailById(row.id).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.getMailList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handlePublicChange (row) {
      this.setPublicStatus(row.id, row.isPublic)
    },

    setPublicStatus (id, isPublic) {
      const mailDTO = { id, isPublic }
      setPublic(mailDTO)
        .then(response => {
          console.log(response)
        })
        .catch(error => {
          // 失败时的处理
          console.error(error)
        })
    },
    handleSizeChange (pageSize) {
      this.searchModel.pageSize = pageSize
      this.getMailList()
    },
    handleCurrentChange (pageNo) {
      this.searchModel.pageNo = pageNo
      this.getMailList()
    },
    getMailList () {
      mailList(this.searchModel).then(response => {
        this.mailList = response.data.rows
        this.total = response.data.total
      })
    }
  }
}
</script>

<style scoped>
.dialog-fade-enter-active, .dialog-fade-leave-active {
  transition: opacity 0.5s;
}
.dialog-fade-enter, .dialog-fade-leave-to {
  opacity: 0;
}
.el-button--primary {
  background-color: #67c23a; /* 修改为绿色 */
  border-color: #67c23a;
}
.el-button--danger {
  background-color: #f56c6c; /* 修改为红色 */
  border-color: #f56c6c;
}
.button-container {
  display: flex;
  justify-content: flex-end; /* 将按钮推到行末尾 */
  margin-top: 10px;
}

.button-container .el-button {
  margin-left: 10px; /* 为按钮添加一些间距 */
}
</style>
